package com.yule.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.yule.config.DynamicDataSourceContext;
import com.yule.config.InitTargetDataSources;
import com.yule.controller.BaseController;
import com.yule.query.Query;
import com.yule.system.home.*;
import com.yule.system.model.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/system/corp")
public class CorpController extends BaseController {

    @Autowired
    private CorpInfoHome corpInfoHome;

    @Autowired
    private SystemUserHome systemUserHome;

    @Autowired
    private SystemRoleHome systemRoleHome;

    @Autowired
    private SystemUserRoleHome systemUserRoleHome;

    @Autowired
    private SystemMenuHome systemMenuHome;

    @Autowired
    private SystemRoleMenuHome systemRoleMenuHome;

    @Value("${dynamic.datasource.prefix.baseUrl}")
    private String prefixBaseUrl;

    @Value("${dynamic.datasource.suffix.baseUrl}")
    private String suffixBaseUrl;

    @Value("${dynamic.datasource.username}")
    private String datasourceUserName;

    @Value("${dynamic.datasource.password}")
    private String datasourcePassword;

    @Value("${dynamic.datasource.driver}")
    private String datasourceDriver;

    @Autowired
    private InitTargetDataSources initTargetDataSources;

    @RequestMapping("/list")
    public ModelAndView list(PageInfo page, Query query){
        DynamicDataSourceContext.setDBType("default");
        PageHelper.startPage(page.getPageNum(), 10);
        Query q = Query.getInstance(query);
        ModelAndView mav = new ModelAndView();
        CorpInfoExample corpInfoExample = new CorpInfoExample();
        CorpInfoExample.Criteria criteria = corpInfoExample.createCriteria();
        if (StringUtils.isNotEmpty(q.getName())) {
            criteria.andCorpNameLike(q.getName());
        }
        corpInfoExample.setOrderByClause("id desc");
        List<CorpInfo> list = corpInfoHome.findList(corpInfoExample);
        PageInfo pageInfo = new PageInfo(list);
        mav.addObject("page", pageInfo);
        mav.addObject("query", query);
        mav.setViewName("system/corp/list");
        return mav;
    }

    @RequestMapping("/add")
    public ModelAndView add(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("system/corp/add");
        return mav;
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable int id){
        DynamicDataSourceContext.setDBType("default");
        ModelAndView mav = new ModelAndView();
        CorpInfo corpInfo = corpInfoHome.findOne(id);
        mav.addObject("model", corpInfo);
        mav.setViewName("system/corp/edit");
        return mav;
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(@ModelAttribute("model") CorpInfo model){
        DynamicDataSourceContext.setDBType("default");
        corpInfoHome.update(model);
        return "redirect:/system/corp/list";
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String delete(@PathVariable int id) {
        DynamicDataSourceContext.setDBType("default");
        if (id != 1) {
            corpInfoHome.delete(id);
        }
        return "redirect:/system/corp/list/";
    }

    @ResponseBody
    @RequestMapping(value = "/checkName/{name}", method = RequestMethod.GET)
    public JSONObject checkName(@PathVariable String name) {
        DynamicDataSourceContext.setDBType("default");
        JSONObject jObject = new JSONObject();
        CorpInfoExample corpInfoExample = new CorpInfoExample();
        CorpInfoExample.Criteria criteria = corpInfoExample.createCriteria();
        if (StringUtils.isNotEmpty(name)) {
            criteria.andLoginCorpNameEqualTo(name);
        }
        List<CorpInfo> list = corpInfoHome.findList(corpInfoExample);
        if (list.size() > 0) {
            jObject.put("rs", false);
        } else {
            jObject.put("rs", true);
        }
        return jObject;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@ModelAttribute("model") CorpInfo model){
        //添加租户信息
        DynamicDataSourceContext.setDBType("default");
        model.setDatasourceUrl(prefixBaseUrl + model.getLoginCorpName() + suffixBaseUrl);
        model.setDatasourceUsername(datasourceUserName);
        model.setDatasourcePassword(datasourcePassword);
        model.setDriverClassName(datasourceDriver);
        corpInfoHome.save(model);
        //刷新动态数据库
        initTargetDataSources.readDataSourcePeriodically();
        //添加租户管理员
        DynamicDataSourceContext.setDBType(model.getLoginCorpName());
        SystemUser user = new SystemUser();
        user.setCorpId(model.getId());
        user.setCorpLoginName(model.getLoginCorpName());
        user.setUsername(model.getLoginCorpName() + "_admin");
        user.setPassword(new SimpleHash("md5","1", ByteSource.Util.bytes("abcd"),2).toString());
        user.setName("系统管理员");
        user.setSalt("abcd");
        user.setIsDel(false);
        user.setIsEnable(true);
        user.setIsSuper(true);
        systemUserHome.save(user);
        //添加租户角色
        SystemRole systemRole = new SystemRole();
        systemRole.setCorpId(model.getId());
        systemRole.setName("系统管理员");
        systemRole.setIsDel(false);
        systemRoleHome.save(systemRole);
        //添加租户管理员与角色管理
        SystemUserRole systemUserRole = new SystemUserRole();
        systemUserRole.setCorpId(model.getId());
        systemUserRole.setUserId(user.getId());
        systemUserRole.setRoleId(systemRole.getId());
        systemUserRoleHome.save(systemUserRole);
        //添加租户角色菜单关联关系
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(146);//菜单管理
        ids.add(172);//租户管理
        ids.add(183);//相关方
        ids.add(184);//相关方下面菜单
        ids.add(189);//相关方下面菜单
        ids.add(246);//流程编辑
        ids.add(177);//BOM管理
        ids.add(178);//成品分类管理
        ids.add(194);//半成品属性管理
        ids.add(199);//原料属性管理
        ids.add(204);//成品管理
        ids.add(209);//半成品管理
        ids.add(214);//原料管理
        ids.add(239);//项目属性管理
        DynamicDataSourceContext.setDBType("default");
        SystemMenuExample systemMenuExample = new SystemMenuExample();
        systemMenuExample.createCriteria().andIdNotIn(ids).andPidNotIn(ids).andPidNotEqualTo(0).andIsDelEqualTo(false);
        List<SystemMenu> menuList = systemMenuHome.findList(systemMenuExample);
        DynamicDataSourceContext.setDBType(model.getLoginCorpName());
        for (SystemMenu systemMenu : menuList) {
            SystemRoleMenu systemRoleMenu = new SystemRoleMenu();
            systemRoleMenu.setCorpId(model.getId());
            systemRoleMenu.setRoleId(systemRole.getId());
            systemRoleMenu.setMenuId(systemMenu.getId());
            systemRoleMenu.setMenuType(systemMenu.getMenuType());
            systemRoleMenuHome.save(systemRoleMenu);
        }
        return "redirect:/system/corp/list";
    }

}
